<?php
/**
 * This file is part of workerman.
 *
 * Licensed under The MIT License
 * For full copyright and license information, please see the MIT-LICENSE.txt
 * Redistributions of files must retain the above copyright notice.
 *
 * @author walkor<walkor@workerman.net>
 * @copyright walkor<walkor@workerman.net>
 * @link http://www.workerman.net/
 * @license http://www.opensource.org/licenses/mit-license.php MIT License
 */

/**
 * 用于检测业务代码死循环或者长时间阻塞等问题
 * 如果发现业务卡死，可以将下面declare打开（去掉//注释），并执行php start.php reload
 * 然后观察一段时间workerman.log看是否有process_timeout异常
 */
//declare(ticks=1);
use \GatewayWorker\Lib\Gateway;

error_reporting(E_ALL ^ E_NOTICE);
require_once __DIR__ . '/Connection.php';

/**
 * 主逻辑
 * 主要是处理 onConnect onMessage onClose 三个方法
 * onConnect 和 onClose 如果不需要可以不用实现并删除
 */
class Events
{
	public static $db = null;
	
 	/**
     * 进程启动后初始化数据库连接
     */
    public static function onWorkerStart($worker)
    {
    	global $pe;
        self::$db = new \Workerman\MySQL\Connection($pe['db_host'], 3306, $pe['db_user'], $pe['db_pw'], $pe['db_name']);
    }

    /**
     * 当客户端连接时触发
     * 如果业务不需此回调可以删除onConnect
     * 
     * @param int $client_id 连接id
     */
    public static function onConnect($client_id)
    {
        // 向当前client_id发送数据 
        //Gateway::sendToClient($client_id, "Hello $client_id\r\n");
        // 向所有人发送
        /*$data['type'] = 'login';
        $data['user'] = Events::userinfo($_GET['user_openid']);
        $data['text'] = '进入直播间'.serialize($_REQUEST);
        $data['allnum'] = Gateway::getAllClientIdList();
		Gateway::sendToAll(json_encode($data));*/
    }
    
	/**
    * 当客户端发来消息时触发
    * @param int $client_id 连接id
    * @param mixed $message 具体消息
    */
	public static function onMessage($client_id, $json)
	{
		global $db;	
	    $json = json_decode($json, true);
	    $user = Events::userinfo($json['user_openid']);
	    switch($json['type'])
	    {
	    	case 'login':
		        //删除已存在记录
		        //$db->pe_delete('chatuser', array('chatuser_code'=>$client_id));
		        self::$db->query("delete from `".dbpre."chatuser` where `chatuser_code` = '".pe_dbhold($client_id)."'");
		        //观看用户入库		        
		        $sql_set['chatuser_atime'] = time();
		        $sql_set['chatuser_code'] = $client_id;
		        $sql_set['user_id'] = $user['user_id'];
		        $sql_set['user_name'] = $user['user_name'];		       	 
		        $sql_set['user_logo'] = $user['user_logo'];
		        //$db->pe_insert('chatuser', pe_dbhold($sql_set)); 		        
		        self::$db->insert(dbpre.'chatuser')->cols(pe_dbhold($sql_set))->query();
		        $data['type'] = 'login';
		        $data['text'] = "欢迎 {$user['user_name']} 进入直播间";
		        $data['user'] = $user;
		        $data['user']['user_logo'] = Events::userlogo($data['user']['user_logo']);
		        $data['user_list'] = Events::user_list();
		        $data['user_num'] = count($data['user_list']);
	    	break;
	    	case 'chat':
		        $data['type'] = 'chat';
		        $data['text'] = $json['text'];
		        $data['user'] = $user;
		        $data['user']['user_logo'] = Events::userlogo($data['user']['user_logo']);
		        //聊天记录入库
		        $sql_set['chat_atime'] = time();
		        $sql_set['chat_text'] = $json['text'];
		        $sql_set['chat_textcode'] = base64_encode($json['text']);
		        $sql_set['user_id'] = $user['user_id'];
		        $sql_set['user_name'] = $user['user_name'];		       	 
		        $sql_set['user_logo'] = $user['user_logo'];
    		    //$db->pe_insert('chat', pe_dbhold($sql_set)); 
		        self::$db->insert(dbpre.'chat')->cols(pe_dbhold($sql_set))->query();
	    	break;
	    }
		Gateway::sendToAll(json_encode($data));
	}
   
	/**
    * 当用户断开连接时触发
    * @param int $client_id 连接id
    */
	public static function onClose($client_id)
	{
			    		echo '【close】';
        $data['type'] = 'logout';
        $data['text'] = '离开直播间';
        $data['user'] = array();
        $data['user_list'] = Events::user_list();
        $data['user_num'] = count($data['user_list']);
        //$data['user_num'] = count(Gateway::getAllClientIdList());
		Gateway::sendToAll(json_encode($data));
	}
	
	public static function userinfo($user_wx_openid) {
		global $db;	
		//$user = $db->pe_select('user', array('user_wx_openid'=>$user_wx_openid));
		$user = self::$db->row("SELECT * FROM `".dbpre."user` WHERE `user_wx_openid` = '".pe_dbhold($user_wx_openid)."'");
		return $user;
	}

	public static function userlogo($user_logo) {
		return pe_thumb($user_logo, 90, 90, 'avatar');
	}
	
	public static function user_list() {
		global $db;	
		$user_list = Gateway::getAllClientIdList();
		//$info_list = $db->pe_selectall('chatuser', array('chatuser_code'=>array_values($user_list)));	
		$info_list = self::$db->query("SELECT * FROM `".dbpre."chatuser` WHERE ".pe_sqlin('chatuser_code', array_values($user_list)));
		foreach ($info_list as $k=>$v) {
			$info_list[$k]['user_logo'] = Events::userlogo($v['user_logo']);
		}
	/*	$db->sql();
		echo PHP_EOL;
		var_dump($info_list);
		echo PHP_EOL;
		echo '------------------';
		echo PHP_EOL;*/
		return $info_list;
	}
}